package com.yehun.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yehun.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * Created by Genius on 2017/5/15 0015.
 */
public class RedisJsonSerializer implements RedisSerializer<Object> {

    private static final Logger logger = LoggerFactory.getLogger(RedisJsonSerializer.class);

    private static final SerializerFeature[] SERIALIZER_FEATURES = {
            SerializerFeature.WriteClassName,
            SerializerFeature.WriteDateUseDateFormat, //格式化日期
            SerializerFeature.WriteMapNullValue, //空值字段输出
            SerializerFeature.WriteNullStringAsEmpty, //字符串为null时输出""
            SerializerFeature.WriteNullListAsEmpty, //列表为null时输出[]
            SerializerFeature.WriteNullBooleanAsFalse, //boolean类型为null时输出false
            SerializerFeature.WriteNullNumberAsZero //整型为null时输出0
    };


    @Override
    public Object deserialize(byte[] bytes) {
        if(bytes == null) {
            return null;
        }
        return JsonUtils.toObject(bytes);
    }

    @Override
    public byte[] serialize(Object object) {
        if(object == null) {
            return null;
        }
        return JsonUtils.toBytes(object, SERIALIZER_FEATURES);
    }

}